/* ============================================================
 * Part of 'Autostop' project
 * Under GPL license - http://www.gnu.org/licenses/gpl.html
 * (c) 2006 - Autostop team
 */

///\file testimage.c test program for image creation, i/o and other

#include "analyzer.h"
#include <stdio.h>
#include <unistd.h>

#define TESTIMAGE_WIDTH		1500
#define TESTIMAGE_HEIGHT	1000
#define TESTIMAGE_PATH		".testmiage"

int main( int argc, char** argv )
{
	pimage_t pimage;
	pimage_t loaded;
	FILE*	outfile;
	FILE*	infile;
	int		counter;

	// say something
	printf("AUTOSTOP image test...\n");

	// create image
	pimage = create_image( TESTIMAGE_WIDTH, TESTIMAGE_HEIGHT );
	if ( ! pimage )
	{
		printf("Creating image failed\n");
		return 1;
	}

	// populate image with 0-255 sequences
	counter = 0;
	{
	foreach_pixel( ppixel, pimage )
	{
		*ppixel = (pixel_t)(counter & 0xff); // use lower 8 bit of counter

		// increment counter
		counter++;
	}
	}
	// check counter value
	if ( counter != TESTIMAGE_WIDTH * TESTIMAGE_HEIGHT )
	{
		printf("Image iteration - counter value invalid: %d got, %d expected\n", counter,
			TESTIMAGE_WIDTH * TESTIMAGE_HEIGHT );
		return 2;
	}
	// save image to file
	outfile = fopen( TESTIMAGE_PATH, "wb" );
	if ( !outfile )
	{
		printf("Could not open %s for writing\n", TESTIMAGE_PATH );
		return 3;
	}

	if ( save_image( outfile, pimage ) )
	{
		printf("Image write error\n");
		unlink( TESTIMAGE_PATH );
		return 4;
	}
	fclose( outfile );
	
	// load image
	infile = fopen( TESTIMAGE_PATH, "rb" );
	if ( !infile )
	{
		printf("Could not open %s for reading\n", TESTIMAGE_PATH );
		return 5;
	}
	
	loaded = load_image( infile );
	fclose( infile );
	unlink( TESTIMAGE_PATH );
	if ( ! loaded )
	{
		printf("Image load error\n");
		return 6;
	}

	// comparte loaded image with written
	if ( loaded->width != pimage->width || loaded->height != pimage->height )
	{
		printf("Image sizes does not match\n");
		return 7;
	}

	counter = 0;
	{
	foreach_pixel( ppixel, loaded )
	{
		if ( *ppixel != (pixel_t)(counter & 0xff) ) // use lower 8 bit of counter
		{
			printf("Loaded/saved image data mismatch at pixel #%d\n", counter);
		}

		// increment counter
		counter++;
	}
	}
	// check counter value
	if ( counter != TESTIMAGE_WIDTH * TESTIMAGE_HEIGHT )
	{
		printf("Image iteration II - counter value invalid: %d got, %d expected\n", counter,
			TESTIMAGE_WIDTH * TESTIMAGE_HEIGHT );
		return 8;
	}
	
	// free images
	free_image( loaded );
	free_image( pimage );
	
	// success
	printf("SUCCESS! All image tests passed.\n");
	return 0;
}

// eof

